<template>
	<div class="order-edit-container" v-loading="loading">
		<!-- 主内容区 -->
		<div class="main-content">
			<!-- 左侧表单区域 -->
			<div class="form-container">
				<h2 class="section-title">订单详情</h2>

				<el-form ref="formRef" :model="form" label-position="top" label-width="120px">
					<!-- 订单基本信息 -->
					<div class="basic-info-grid">
						<!-- 订单编号 -->
						<el-form-item label="订单编号">
							<el-input v-model="form.orderNumber" disabled />
						</el-form-item>

						<!-- 用户ID -->
						<el-form-item label="用户ID">
							<el-input v-model="form.userId" disabled />
						</el-form-item>

						<!-- 用户电话 -->
						<el-form-item label="用户电话">
							<el-input v-model="form.userPhone" disabled />
						</el-form-item>

						<!-- 订单类型 -->
						<el-form-item label="订单类型">
							<el-input :value="getOrderTypeText(form.orderType)" disabled />
						</el-form-item>

						<!-- 订单状态 -->
						<el-form-item label="订单状态">
							<el-input :value="getOrderStatusText(form.orderStatus)" disabled />
						</el-form-item>

						<!-- 支付状态 -->
						<el-form-item label="支付状态">
							<el-input :value="getPaymentStatusText(form.paymentStatus)" disabled />
						</el-form-item>

						<!-- 支付方式 -->
						<el-form-item label="支付方式">
							<el-input v-model="form.paymentMethod" disabled />
						</el-form-item>

						<!-- 交易ID -->
						<el-form-item label="交易ID">
							<el-input v-model="form.transactionId" disabled />
						</el-form-item>

						<!-- 订单金额 -->
						<el-form-item label="订单金额">
							<el-input :value="'¥' + form.totalAmount" disabled />
						</el-form-item>
					</div>

					<!-- 可退款状态模块 -->
					<div class="refund-status-container">
						<h3 class="refund-title">退款状态</h3>
						<div class="refund-content">
							<el-tag :type="refundStatus.isRefundable ? 'success' : 'danger'" size="large">
								{{ refundStatus.isRefundable ? '可退款' : '不可退款' }}
							</el-tag>
							<el-button type="primary" @click="handleUpdateRefundStatus"
								:disabled="!refundStatus.isRefundable || refundStatus.updating"
								:loading="refundStatus.updating">
								{{ refundStatus.isRefundable ? '设为不可退款' : '设为可退款' }}
							</el-button>
						</div>
						<div class="refund-tip" v-if="refundStatus.remark">
							<el-icon>
								<InfoFilled />
							</el-icon>
							<span>备注：{{ refundStatus.remark }}</span>
						</div>
					</div>

					<!-- 订单备注 -->
					<el-form-item label="订单备注" prop="remark">
						<el-input v-model="form.remark" type="textarea" :rows="5" resize="vertical" />
					</el-form-item>

					<!-- 创建时间 -->
					<el-form-item label="创建时间">
						<el-input :value="formatDateTime(form.createdAt)" disabled />
					</el-form-item>

					<!-- 更新时间 -->
					<el-form-item label="更新时间">
						<el-input :value="formatDateTime(form.updatedAt)" disabled />
					</el-form-item>
				</el-form>
			</div>
		</div>

		<!-- 底部操作栏 -->
		<div class="bottom-bar">
			<el-button @click="handleCancel">返回</el-button>
			<div class="right-buttons">
				<el-button type="primary" @click="handleSubmit">保存修改</el-button>
			</div>
		</div>

		<!-- 修改退款状态对话框 -->
		<el-dialog v-model="refundDialog.visible" title="修改退款状态" width="500px">
			<el-form :model="refundDialog.form" label-width="100px">
				<el-form-item label="退款备注" required>
					<el-input v-model="refundDialog.form.remark" type="textarea" :rows="3" placeholder="请输入修改退款状态的原因"
						resize="vertical" />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="refundDialog.visible = false">取消</el-button>
					<el-button type="primary" @click="confirmUpdateRefundStatus" :loading="refundDialog.loading">
						确认修改
					</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		name: 'OrderEditView',
	};
</script>

<script setup>
	import {
		ref,
		reactive,
		onMounted
	} from "vue";
	import {
		useRoute,
		useRouter
	} from 'vue-router'
	import {
		ElMessage,
		ElMessageBox
	} from "element-plus";
	import {
		InfoFilled
	} from '@element-plus/icons-vue'
	import {
		getOrderDetails,
		updateOrder,
		enableRefundStatus,
		getIsRefundable
	} from '@/api/order.js'

	const router = useRouter()
	const route = useRoute()
	const id = route.params.id
	const loading = ref(false)

	/**
	 * 表单数据
	 */
	const form = ref({
		id: "",
		orderNumber: "",
		userId: "",
		userPhone: "",
		orderType: 0,
		totalAmount: "0.00",
		orderStatus: 0,
		paymentStatus: 0,
		paymentMethod: "",
		transactionId: "",
		remark: "",
		createdAt: "",
		updatedAt: ""
	});

	/**
	 * 退款状态相关
	 */
	const refundStatus = reactive({
		isRefundable: false,
		remark: '',
		updating: false
	})

	/**
	 * 退款状态对话框
	 */
	const refundDialog = reactive({
		visible: false,
		loading: false,
		form: {
			remark: ''
		}
	})

	/**
	 * 订单类型选项
	 */
	const orderTypeOptions = [{
			value: 1,
			label: "商品订单"
		},
		{
			value: 2,
			label: "课程订单"
		},
		{
			value: 3,
			label: "包间订单"
		}
	];

	/**
	 * 订单状态选项
	 */
	const orderStatusOptions = [{
			value: 0,
			label: "待支付"
		},
		{
			value: 1,
			label: "已支付"
		},
		{
			value: 2,
			label: "已完成"
		},
		{
			value: 3,
			label: "已取消"
		},
		{
			value: 4,
			label: "已退款"
		}
	];

	/**
	 * 支付状态选项
	 */
	const paymentStatusOptions = [{
			value: 0,
			label: "未支付"
		},
		{
			value: 1,
			label: "支付中"
		},
		{
			value: 2,
			label: "已支付"
		},
		{
			value: 3,
			label: "支付失败"
		},
		{
			value: 4,
			label: "已退款"
		}
	];

	/**
	 * 获取订单类型文本
	 */
	const getOrderTypeText = (type) => {
		const option = orderTypeOptions.find(item => item.value === type);
		return option ? option.label : "未知类型";
	};

	/**
	 * 获取订单状态文本
	 */
	const getOrderStatusText = (status) => {
		const option = orderStatusOptions.find(item => item.value === status);
		return option ? option.label : "未知状态";
	};

	/**
	 * 获取支付状态文本
	 */
	const getPaymentStatusText = (status) => {
		const option = paymentStatusOptions.find(item => item.value === status);
		return option ? option.label : "未知状态";
	};

	/**
	 * 格式化日期时间
	 */
	const formatDateTime = (dateString) => {
		if (!dateString) return '';
		const date = new Date(dateString);
		return date.toLocaleString();
	};

	/**
	 * 获取订单详情和退款状态
	 */
	const fetchOrderData = async () => {
		loading.value = true;
		try {
			// 获取订单基本信息
			const orderRes = await getOrderDetails(id);
			if (orderRes.code === 200 && orderRes.data) {
				form.value = orderRes.data;
				ElMessage.success(orderRes.message || '获取数据成功');
			} else {
				ElMessage.error(orderRes.message || '获取订单详情失败');
			}

			// 获取退款状态
			const refundRes = await getIsRefundable(id);
			if (refundRes.code === 200 && refundRes.data) {
				refundStatus.isRefundable = refundRes.data.isRefundable === 1;
				refundStatus.remark = refundRes.data.remark || '';
			} else {
				console.log(refundRes.code, refundRes.data);
				ElMessage.error('获取退款状态失败');
			}
		} catch (error) {
			ElMessage.error('获取数据失败');
		} finally {
			loading.value = false;
		}
	};

	/**
	 * 提交订单备注修改
	 */
	const handleSubmit = async () => {
		try {
			// 构造要提交的数据
			const submitData = {
				id: form.value.id,
				remark: form.value.remark
			};

			const res = await updateOrder(submitData);
			if (res.code === 200 || res.code === 204) {
				ElMessage.success(res.message || '修改成功');
				fetchOrderData(); // 重新加载数据
			} else {
				ElMessage.error(res.message || '修改失败');
			}
		} catch (error) {
			console.error('提交失败:', error);
			ElMessage.error(`操作失败: ${error.message || '请检查数据'}`);
		}
	};

	/**
	 * 打开修改退款状态对话框
	 */
	const handleUpdateRefundStatus = () => {
		refundDialog.form.remark = '';
		refundDialog.visible = true;
	};

	/**
	 * 确认修改退款状态
	 */
	const confirmUpdateRefundStatus = async () => {
		if (!refundDialog.form.remark) {
			ElMessage.warning('请输入修改退款状态的原因');
			return;
		}

		refundDialog.loading = true;
		try {
			const res = await enableRefundStatus({
				orderId: id,
				remark: refundDialog.form.remark
			});

			if (res.code === 200) {
				ElMessage.success('退款状态更新成功');
				refundDialog.visible = false;
				fetchOrderData(); // 重新加载数据
			} else {
				ElMessage.error(res.message || '退款状态更新失败');
			}
		} catch (error) {
			ElMessage.error('退款状态更新失败');
		} finally {
			refundDialog.loading = false;
		}
	};

	/**
	 * 取消编辑
	 */
	const handleCancel = () => {
		ElMessageBox.confirm("确定放弃当前编辑的内容吗？", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			})
			.then(() => {
				ElMessage.info("已取消编辑");
				router.back();
			})
			.catch(() => {});
	};

	onMounted(() => {
		fetchOrderData();
	});
</script>

<style scoped>
	.order-edit-container {
		min-height: 100vh;
		background-color: #f9fafb;
		padding: 20px;
		height: 95%;
		min-height: 0;
		overflow-y: auto;
	}

	.section-title {
		font-size: 1.25rem;
		font-weight: 600;
		margin-bottom: 1.5rem;
	}

	.main-content {
		display: flex;
		gap: 20px;
		flex-wrap: wrap;
	}

	.form-container {
		flex: 1;
		min-width: 300px;
		background-color: white;
		padding: 20px;
		border-radius: 4px;
		box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
	}

	.bottom-bar {
		margin-top: 20px;
		padding: 15px 20px;
		background-color: white;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.right-buttons {
		display: flex;
		gap: 10px;
	}

	.basic-info-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 1.5rem;
	}

	/* 退款状态模块样式 */
	.refund-status-container {
		margin: 20px 0;
		padding: 15px;
		background-color: #f8f9fa;
		border-radius: 4px;
		border-left: 4px solid var(--el-color-primary);
	}

	.refund-title {
		font-size: 1rem;
		font-weight: 500;
		margin-bottom: 12px;
		color: #606266;
	}

	.refund-content {
		display: flex;
		align-items: center;
		gap: 20px;
		margin-bottom: 10px;
	}

	.refund-tip {
		font-size: 0.875rem;
		color: #909399;
		display: flex;
		align-items: center;
		gap: 5px;
	}

	/* 禁用状态的输入框样式 */
	:deep(.el-input.is-disabled .el-input__inner) {
		color: #606266;
		background-color: #f5f7fa;
		border-color: #e4e7ed;
		cursor: not-allowed;
	}

	.dialog-footer {
		text-align: right;
	}
</style>